from django.shortcuts import render
from django.conf import settings
from django_redis import get_redis_connection
from django.views import View
from ronglian_sms_sdk import SmsSDK
from django.http import JsonResponse, HttpResponse
from libs.captcha.captcha import captcha
from apps.users.models import User
import random
import json
import logging
from celery_tasks.sms.tasks import sms_send
logger = logging.getLogger('django')
# Create your views here.
# 短信验证码
class SmsCodeView(View):
    def get(self, request, mobile):
        '''短信验证码'''
        # 接受参数
        # 判断手机号是否重复注册
        redis_conn = get_redis_connection('code')
        pl = redis_conn.pipeline()

        image_code_clent = request.GET.get('image_code')
        uuid_clent = request.GET.get('image_code_id')

        # 效验参数
        mobile_mun = redis_conn.get(mobile)
        if mobile_mun != None:
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码发送频繁'})


        mobile_count = User.objects.filter(modile=mobile).count()
        if not mobile_count == 0:
            return JsonResponse({'code': 400,
                                 'errmsg': '手机号重复注册'})

        image_code_server = redis_conn.get('img_%s' % uuid_clent)
        if image_code_server == None:
            return JsonResponse({'code': 400,
                                 'errmsg': '图片验证码失效'})
        image_code_server = image_code_server.decode()
        if image_code_server.lower() != image_code_clent.lower():
            return JsonResponse({'code': 400,
                                 'errmsg': '验证码错误'})
        redis_conn.delete('img_%s' % uuid_clent)

        # 生成验证码保存
        mobile_sms = '%04d' % random.randint(0, 9999)
        logger.info(mobile_sms)
        pl.setex('sms_%s' % mobile, 60, mobile_sms)
        send_data = (mobile_sms,)
        # sms = SmsSDK(settings.ACCID, settings.ACCTOKEN, settings.APPID)

        # 发短信使用celery异步

        try:
            # sms.sendMessage('1', mobile, send_data)
            sms_send.delay(mobile, send_data)
        except Exception as e:
                logger.error(e)

        # 标记手机号
        pl.setex(mobile, 200, 1)
        # 提交管道
        pl.execute()
        return JsonResponse({'code': 0,
                                 'errmsg': 'ok'})


# =======================================================================================================
# 图片验证码
class ImageCodeView(View):
    def get(self, request, uuid):
        '''图片验证码'''
        # 生成验证码
        text, image = captcha.generate_captcha()
        if not all([text, image]):
            logger.error('生成验证码失败')
        logger.info(text)
        # 保存验证码
        redis_conn = get_redis_connection('code')
        try:
            redis_conn.setex('img_%s' % uuid, 60, text)
        except Exception as e:
            logger.error('e')


        # 返回验证码

        return HttpResponse(image, content_type='image/jpeg')


